import 'package:inmotion_pro/l10n/local.dart';
import 'package:intl/intl.dart';

import 'string_util.dart';

// 日期格式化工具类
class DateFormatUtil {
  static String formatTimestamp(int millisecondsSinceEpoch) {
    final DateTime now = DateTime.now();
    final DateTime date =
        DateTime.fromMillisecondsSinceEpoch(millisecondsSinceEpoch);
    final Duration difference = now.difference(date);

    // 如果是今天
    if (difference.inDays == 0) {
      if (difference.inHours > 0) {
        return local.hours_ago(difference.inHours);
      } else if (difference.inMinutes > 0) {
        return local.minutes_ago(difference.inMinutes);
      } else {
        return local.just_now;
      }
    } else if (difference.inDays == 1) {
      // 如果是昨天
      return local.yesterday;
    } else if (now.year == date.year) {
      // 如果是今年
      return DateFormat('M/d HH:mm').format(date); // 例如: "10月5日 14:30"
    } else {
      // 其他情况（跨年）
      return DateFormat('yyyy/M/d HH:mm')
          .format(date); // 例如: "2023年10月5日 14:30"
    }
  }

  // 根据月份数字获取月份名称
  static String getMonth(int month) {
    switch (month) {
      case 1:
        return local.january;
      case 2:
        return local.february;
      case 3:
        return local.march;
      case 4:
        return local.april;
      case 5:
        return local.may;
      case 6:
        return local.june;
      case 7:
        return local.july;
      case 8:
        return local.august;
      case 9:
        return local.september;
      case 10:
        return local.october;
      case 11:
        return local.november;
      case 12:
        return local.december;
      default:
        return '';
    }
  }

  // 时间戳转 DateTime
  static DateTime getDate(int stamp) {
    String str = "$stamp";
    if (str.length > 13) {
      str = "${DateTime.now().millisecondsSinceEpoch}";
    } else if (str.length < 13) {
      str = LxStringUtil.padRight(13, "$stamp", "0");
    }
    return DateTime.fromMillisecondsSinceEpoch(int.parse(str));
  }

  // 解析日期字符串，支持多种格式和时间戳
  static DateTime? parseDateString(String? dateStr, [List<String>? formats]) {
    if (dateStr == null || dateStr.trim().isEmpty) return null;

    final trimmed = dateStr.trim();

    // 优先尝试标准格式
    try {
      return DateTime.parse(trimmed);
    } catch (_) {}

    // 尝试预定义格式
    final defaultFormats = formats ??
        [
          'yyyy-MM-dd HH:mm:ss',
          'yyyy-MM-dd',
          'yyyy/MM/dd HH:mm:ss',
          'yyyy/MM/dd',
          'MM/dd/yyyy HH:mm:ss',
          'MM/dd/yyyy',
        ];

    for (final format in defaultFormats) {
      try {
        return DateFormat(format).parse(trimmed);
      } catch (_) {}
    }

    // 尝试时间戳
    if (RegExp(r'^\d+$').hasMatch(trimmed)) {
      final timestamp = int.tryParse(trimmed);
      if (timestamp != null) {
        final millis = timestamp > 1000000000000 ? timestamp : timestamp * 1000;
        return DateTime.fromMillisecondsSinceEpoch(millis);
      }
    }

    return null;
  }
}
